package com.career.syn.websocket.basic;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author guxiaowei
 * @version 1.0
 * @date 2020/8/17 15:27
 * @Description:
 */
@ServerEndpoint(value = "/websocket1")
@Component
public class WebSocketServer {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 使用ConcurrentHashSet, 放的是WebSocketServer而不是session为了复用自己方法
     */
    private static transient volatile Set<WebSocketServer> webSocketSet = ConcurrentHashMap.newKeySet();

    private ConcurrentHashMap<String,Session> socketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        socketMap.put(userId,session);
        sendMessage("连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("来自客户端(" + session.getId() + ")的消息:" + message);
        sendMessage("Hello, nice to hear you! There are " + webSocketSet.size() + " users like you in total here!");
        Map<String,Object> map = new HashMap<>();
        map.put("1","1111");
        map.put("2","22222");
        sendInfo(JSONObject.toJSONString(map));
    }

    /**
     * Title: onError
     * Description: 发生错误时候回调函数
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        if (session.isOpen()){
//            session.close();
        }
        logger.error("webSocket发生错误:" + error.getClass() + error.getMessage());
    }

    /**
     * Title: sendMessage
     * Description: 向客户端发送消息
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException error) {
            logger.error("webSocket-sendMessage发生错误:" + error.getClass() + error.getMessage());
        }
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) {
        logger.info("webSocket-sendInfo群发消息：" + message);
        for (WebSocketServer item : webSocketSet) {
            item.sendMessage(message);
        }
    }

    /**
     * Title: getOnlineCount
     * Description: 获取连接数
     *
     * @return
     */
    public static int getOnlineCount() {
        return webSocketSet.size();
    }
}